// 日志sdk
class logger {
  constructor(ctx) {
    ctx = ctx || {};
    if (!ctx || typeof ctx._emitter != "object") {
      throw new Error('初始化消息发送器模块时，请传入_emitter对象');
    }
    // 根据参数判定logger是否显示
    this._loggerShow = ctx.loggerShow || false;
    this._mfutil = ctx._that || "";
    this._emitter = ctx._emitter || "";  // 发送消息对象
    this._cloud = ctx._cloud || "";  // 云
    this._loggerArray = [{
      name: "日志",
      tag: 1,
      logArray: []
    }];
    // 如果需要显示，去取一下用户的白名单,需要等待用户模块先去获取
    if (!this._loggerShow) {
      setTimeout(() => {
        this.getUserLoggerShow();
      }, 1500);
    }
  }

  //  消息发送器
  async set({ origin, msg }) {
    const msgstr = typeof msg == 'string' ? msg : JSON.stringify(msg);
    this._loggerArray[0].logArray.push({
      origin: origin,
      data: msgstr
    });
    this._emitter.emit("logger-topic", { data: this._loggerArray });
    return true;
  }

  // 简化的消息发送器
  async log(msg, origin = '', ifLog = true) {
    if (ifLog) console.log(msg, origin);
    const msgstr = typeof msg == 'string' ? msg : JSON.stringify(msg);
    this._loggerArray[0].logArray.push({
      origin: origin,
      data: msgstr
    });
    this._emitter.emit("logger-topic", { data: this._loggerArray });
    return true;
  }

  // 获取消息
  async get() {
    return this._loggerArray;
  }

  //  清除所有的消息
  async clear() {
    this._loggerArray[0].logArray = [];
    this._emitter.emit("logger-topic", { data: this._loggerArray });
  }

  // 获取用户信息
  async getUserLoggerShow() {
    if (this._mfutil.userAccess) {
      const userInfo = await this._mfutil.userAccess.get();
      if (userInfo && userInfo.loggerShow) {
        this._loggerShow = true;
        this._emitter.emit('changeLoggerShow');
      }
    }
  }

  // 设置用户可以展示 logger 的方法，上线的时候请主动关闭
  async setUserLoggerShow(loggerShow = true) {
    if (this._mfutil.userAccess) {
      await this._mfutil.userAccess.insertKey({ loggerShow });
    }
  }

  // 获取 LoggerShow
  async getLoggerShow() {
    return this._loggerShow;
  }

  // 设置 LoggerShow
  async setLoggerShow(loggerShow = true) {
    this._loggerShow = loggerShow;
    this._emitter.emit('changeLoggerShow');
  }

  // 记录错误日志
  async error(text, origin = 'errorLogger') {
    await this.log(text, origin);
    await this._cloud.ajax({ name: 'systemAccessCloud', data: { text, level: 'error' }, handler: 'addLogger' }, 'cloud_fun');
  }

  // 记录日志
  async info(text, origin = 'infoLogger') {
    await this.log(text, origin);
    await this._cloud.ajax({ name: 'systemAccessCloud', data: { text }, handler: 'addLogger' }, 'cloud_fun');
  }

}

module.exports = exports.logger = logger;